//
//  UIUtil.m
//  
//
//  Created by liuhui on 12-9-11.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "UIUtil.h"

#import "AppDelegate.h"

#import <CommonCrypto/CommonDigest.h>

#import <QuartzCore/QuartzCore.h>
#import <AudioToolbox/AudioToolbox.h>
#import "Reachability.h"
#import "MBProgressHUD+WZ.h"
#import <AVFoundation/AVFoundation.h>
#import "MicroDef.h"
#import "CFileModel.h"
#import "RegexKitLite.h"
#import "CXmppRequestMgr.h"
#import "DownloadFileManager.h"
#import "CUserSettingModel.h"



#define CC_MD5_DIGEST_LENGTH	16	/* digest length in bytes */
#define CC_MD5_BLOCK_BYTES		64	/* block size in bytes */
#define kTagHintMessageView		9876
#define kSecondsOfDay			24*60*60
#define kTagIndicator           1234567
#define kTagIndicatorView       1234569

@implementation UIUtil


void IMSystemSoundFinishedPlayingCallback(SystemSoundID sound_id, void* user_data)
{
    AudioServicesDisposeSystemSoundID(sound_id);
}


+(UIView*)getAViewWithSize:(CGSize)si backGroundColor:(UIColor*)color
{
    UIView* vifoot = [[UIView alloc]initWithFrame:CGRectMake(0, 0, si.width, si.height)];
    [vifoot setBackgroundColor:color];
    return vifoot;
}

//+(CGFloat)voiceTimeForRowAtIndexPath:(NSString *)fileUri
//{
//    NSString *path = [NSString stringWithFormat:@"%@%@",[[ChildHoodService defaultService].childHoodUser getResourcePath],fileUri];
//    NSData *data = [NSData dataWithContentsOfFile:path];
//    if(data == nil){
//        NSString *path = [NSString stringWithFormat:@"%@%@",[[ChildHoodService defaultService].childHoodUser getResourcePath], [UIUtil md5:fileUri]];
//        data = [NSData dataWithContentsOfFile:path];
//    }
//    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
//    CGFloat time = player.duration;
//    return time;
//}

//+ (NSMutableDictionary *)initAccountPlist
//{
//    NSMutableDictionary *account = nil;
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//    NSString *plistPath = [paths objectAtIndex:0];
//    NSString *filename = [plistPath stringByAppendingPathComponent:@"account.plist"];
//    BOOL isExist = [[NSFileManager defaultManager] fileExistsAtPath:filename];
//    if (!isExist) {
//        NSLog(@"account.plist不存在");
//        NSMutableDictionary *data = [[NSMutableDictionary alloc] init] ;
//        [data setObject:@"" forKey:@"Username"];
//        [data setObject:@"" forKey:@"Password"];
//        [data setObject:[NSNumber numberWithInteger:SNSPRelativeTypeKSelf] forKey:@"RelativeType"];
//        [data setObject:[NSNumber numberWithBool:NO] forKey:@"RemeberPassword"];
//        [data setObject:[NSNumber numberWithBool:NO] forKey:@"AutoLogin"];
////        [data setObject:nil forKey:@""];
//        NSLog(@"创建account.plist保存到本地");
//        [data writeToFile:filename atomically:YES];
//    }
//    else
//    {
//        NSLog(@"account.plist已经存在");
//        account = [[NSMutableDictionary alloc] initWithContentsOfFile:filename];
//    }
//    return account;
//}
//
//+ (void )updateAccountPlist:(NSDictionary *)account
//{
//    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
//    NSString *plistPath = [paths objectAtIndex:0];
//    NSString *filename = [plistPath stringByAppendingPathComponent:@"account.plist"];
//    [account writeToFile:filename atomically:YES];
//    return;
//}


+(void)addMBProgressViewTitle:(NSString*)title inView:(UIView*)view alpha:(CGFloat)al failureTitle:(NSString *)failureTitle
{
    if ([UIUtil isNetworkReachable]) {
        MBProgressHUD *progress = [[MBProgressHUD alloc] initWithView:view];
        progress.removeFromSuperViewOnHide = YES;
        progress.labelText = title;
        [progress setAlpha:al];
        [view addSubview:progress];
        [view bringSubviewToFront:progress];
        [progress show:YES];
    }else
    {
        [MBProgressHUD showError:failureTitle];
    }
}

+(void)addMBProgressViewTitle:(NSString*)title inView:(UIView*)view alpha:(CGFloat)al hideDelayTime:(NSTimeInterval)time failureTitle:(NSString *)failureTitle
{
    if ([UIUtil isNetworkReachable]) {
        MBProgressHUD *progress = [[MBProgressHUD alloc] initWithView:view];
        progress.removeFromSuperViewOnHide = YES;
        progress.labelText = title;
        [progress setAlpha:al];
        [view addSubview:progress];
        [view bringSubviewToFront:progress];
        [progress show:YES];
        [progress hide:YES afterDelay:time];
    }else
    {
        [MBProgressHUD showError:failureTitle];
    }
}

+(void)addMBProgressViewNoNetWorcCheckTitle:(NSString*)title inView:(UIView*)view alpha:(CGFloat)al failureTitle:(NSString *)failureTitle
{
    MBProgressHUD *progress = [[MBProgressHUD alloc] initWithView:view];
    progress.removeFromSuperViewOnHide = YES;
    progress.labelText = title;
    [progress setAlpha:al];
    [view addSubview:progress];
    [view bringSubviewToFront:progress];
    [progress show:YES];
}


+(void)hideMBProgressViewForView:(UIView*)view
{
    [MBProgressHUD hideAllHUDsForView:view animated:YES];
}

+(BOOL)MBProgressViewForView:(UIView*)view
{
    return [MBProgressHUD isHUDsForView:view];
}

+ (NSString *)timeFormatConvert:(NSDate *)date
{
    NSString *result = nil;
//    NSLog(@"target Date:%@",date);
    
    NSDate *localeDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
    NSDate *curDate = [localeDate dateByAddingTimeInterval: interval];
//    NSLog(@"current Date:%@",curDate);
    
    NSInteger day = [[UIUtil getDayFromDate:date] integerValue];
//    NSLog(@"target Day:%d",day);
    
    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
//    NSLog(@"current Day:%d",curDay);
    
    if (day == curDay) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
        [formatter setAMSymbol:@"上午"];
        [formatter setPMSymbol:@"下午"];
        [formatter setDateFormat:@"aa HH:mm"];
        result = [formatter stringFromDate:date];
    }
    else if ((curDay - day)==1)
    {
        result = @"昨天";
    }
    else if ((curDay - day)>1)
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM月dd日 "];
        result = [formatter stringFromDate:date];
    }
    else
    {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"MM月dd日"];
        result = [formatter stringFromDate:date];
    }

    return result;
}

+ (NSString*)timeForCommentListStyle:(NSDate*) theDate
{
    NSTimeZone *z = [NSTimeZone systemTimeZone];
    NSInteger val = [z secondsFromGMTForDate:theDate];
    NSDate *tDate = [theDate dateByAddingTimeInterval: val];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
    NSString *targetDate = [formatter stringFromDate:tDate];
    
    NSString *timeString = nil;
    
    NSInteger year = [[targetDate substringWithRange:NSMakeRange(0, 4)] integerValue];
    NSInteger month = [[targetDate substringWithRange:NSMakeRange(5, 2)] integerValue];
    NSInteger day = [[targetDate substringWithRange:NSMakeRange(8, 2)] integerValue];
//    NSLog(@"target:%d %d %d",year,month,day);
    
    NSTimeInterval time = ([[NSDate date] timeIntervalSince1970] * 1000) + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    NSDate *localeDate = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];

    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
    NSDate *curDate = [localeDate dateByAddingTimeInterval: interval];
    
    NSInteger curYear = [[UIUtil getYearFromDate:curDate] integerValue];
    NSInteger curMonth = [[UIUtil getMonthFromDate:curDate] integerValue];
    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
//    NSLog(@"current:%d %d %d",curYear,curMonth,curDay);
    
    NSInteger yearCha = curYear - year;
    NSInteger monthCha = curMonth - month;
    NSInteger dayCha = curDay - day;
    
    NSString *HMTime = [targetDate substringWithRange:NSMakeRange(12,5)];
    //当年
    if (yearCha == 0) {
        //当月
        if (monthCha == 0) {
            //当天
            if (dayCha == 0) {
                timeString = HMTime;
            }
            //昨天
            else if (dayCha == 1)
            {
                timeString = [NSString stringWithFormat:@"昨天 %@",HMTime];
            }
            else
            {
                timeString = [targetDate substringWithRange:NSMakeRange(5, [targetDate length]-5)];
            }
        }
        else
        {
            timeString = [targetDate substringWithRange:NSMakeRange(5, [targetDate length]-5)];
        }
    }
    else
    {
        timeString = targetDate;
    }
    return timeString;
}

+ (NSString*)timeForMessageStyle:(NSDate *)theDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone systemTimeZone]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm EEEE"];
    NSString *targetDate = [formatter stringFromDate:theDate];

    NSString *timeString = nil;

    NSInteger month = [[targetDate substringWithRange:NSMakeRange(5, 2)] integerValue];
//    NSLog(@"target Month:%d",month);
    
    NSInteger day = [[targetDate substringWithRange:NSMakeRange(8, 2)] integerValue];
//    NSLog(@"target Day:%d",day);
    
    NSTimeInterval time = ([[NSDate date] timeIntervalSince1970] * 1000) + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    
    NSDate *localeDate = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];
//     NSLog(@"--%@",localeDate);
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
    NSDate *curDate = [localeDate dateByAddingTimeInterval:interval];
//    NSLog(@"--%@",curDate);
    
    NSInteger curMonth = [[UIUtil getMonthFromDate:curDate] integerValue];
//    NSLog(@"current Month:%d",curMonth);
    
    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
//    NSLog(@"current Day:%d",curDay);
    
    NSInteger monthCha = curMonth - month;
    NSInteger dayCha = curDay - day;
    
    
    
//    NSLog(@"%zd  %zd %zd %zd",monthCha,dayCha,curMonth,curDay);
    NSString *HMTime = [targetDate substringWithRange:NSMakeRange(12,5)];
    //当月
    if (monthCha == 0) {
        //当天
        if (dayCha == 0) {
            timeString = HMTime;
        }
        //昨天
        else if (dayCha == 1)
        {
            timeString = [NSString stringWithFormat:@"昨天 %@",HMTime];
        }
        //第三天至第七天之内（包含第七天）
        else if (dayCha > 1 && dayCha < 7)
        {
            timeString = [NSString stringWithFormat:@"%@ %@",[targetDate substringFromIndex:18],HMTime];
        }
        //大于七天
        else
        {
            timeString = [targetDate substringToIndex:17];
        }
    }
    //第二个月以上
    else
    {
        timeString = [targetDate substringToIndex:17];
    }
    return timeString;
}


+ (NSString*)timeForMessageStyleNew:(NSDate *)theDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm"];
//    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm EEEE"];
    NSString *targetDate = [formatter stringFromDate:theDate];
    
    NSString *timeString = nil;
    
    NSInteger month = [[targetDate substringWithRange:NSMakeRange(5, 2)] integerValue];
    //    NSLog(@"target Month:%d",month);
    
    NSInteger day = [[targetDate substringWithRange:NSMakeRange(8, 2)] integerValue];
    NSInteger year =[[targetDate substringWithRange:NSMakeRange(0, 4)] integerValue];
    //    NSLog(@"target Day:%d",day);
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000 + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    
    
   
    NSDate *localeDate = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
    NSDate *curDate = [localeDate dateByAddingTimeInterval: interval];
//        NSLog(@"--%@",curDate);
    
    NSInteger curMonth = [[UIUtil getMonthFromDate:curDate] integerValue];
    //    NSLog(@"current Month:%d",curMonth);
    
    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
    NSInteger curYear =[[UIUtil getYearFromDate:curDate] integerValue];
    //    NSLog(@"current Day:%d",curDay);
    
    NSInteger monthCha = curMonth - month;
    NSInteger dayCha = curDay - day;
    
    NSString *HMTime = [targetDate substringWithRange:NSMakeRange(12,5)];
    //当月
    if (monthCha == 0) {
        //当天
        if (dayCha == 0) {
            timeString = [NSString stringWithFormat:@"今天 %@",HMTime];;
        }
        //昨天
        else if (dayCha == 1)
        {
            timeString = [NSString stringWithFormat:@"昨天 %@",HMTime];
        }
        else if (dayCha == 2)
        {
            timeString = [NSString stringWithFormat:@"前天 %@",HMTime];
        }
        //第三天至第七天之内（包含第七天）
//        else if (dayCha > 2 && dayCha < 7)
//        {
//            timeString = [NSString stringWithFormat:@"%@ %@",[targetDate substringFromIndex:18],HMTime];
//        }
        //大于七天
        else
        {
            timeString = [NSString stringWithFormat:@"%d日 %@",day,HMTime];
        }
    }
    //第二个月以上
    else
    {
        if(curYear == year)
        {
            timeString = [targetDate substringFromIndex:5];
        }
        else
        {
            timeString = [targetDate substringFromIndex:2];
        }
    }
    return timeString;
}

+ (NSString*)timeForMessageListStyle:(NSDate*) theDate;
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm EEEE"];
    NSString *targetDate = [formatter stringFromDate:theDate];
    
    NSString *timeString = nil;
    
    NSInteger month = [[targetDate substringWithRange:NSMakeRange(5, 2)] integerValue];
//    NSLog(@"target Month:%d",month);
    
    NSInteger day = [[targetDate substringWithRange:NSMakeRange(8, 2)] integerValue];
//    NSLog(@"target Day:%d",day);
    
    NSDate *localeDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
    NSDate *curDate = [localeDate dateByAddingTimeInterval: interval];
    
    NSInteger curMonth = [[UIUtil getMonthFromDate:curDate] integerValue];
//    NSLog(@"current Month:%d",curMonth);
    
    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
//    NSLog(@"current Day:%d",curDay);
    
    NSInteger monthCha = curMonth - month;
    NSInteger dayCha = curDay - day;
    
    NSString *HMTime = [targetDate substringWithRange:NSMakeRange(11,5)];
    //当月
    if (monthCha == 0) {
        //当天
        if (dayCha == 0) {
            timeString = HMTime;
        }
        //昨天
        else if (dayCha == 1)
        {
            timeString = @"昨天";
        }
        //第三天至第七天之内（包含第七天）
        else if (dayCha > 1 && dayCha < 7)
        {
            timeString = [targetDate substringFromIndex:17];
        }
        //大于七天
        else
        {
            timeString = [targetDate substringWithRange:NSMakeRange(2, 8)];
        }
    }
    //第二个月以上
    else
    {
        timeString = [targetDate substringWithRange:NSMakeRange(2, 8)];
    }
    return timeString;
}

+ (NSAttributedString *)timeForMineShareListStyle:(NSDate*) theDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"yyyy年MM月dd日 HH:mm EEEE"];
    NSString *targetDate = [formatter stringFromDate:theDate];
    
    NSAttributedString *timeString = nil;
    
    NSInteger month = [[targetDate substringWithRange:NSMakeRange(5, 2)] integerValue];
    //    NSLog(@"target Month:%d",month);
    
    NSInteger day = [[targetDate substringWithRange:NSMakeRange(8, 2)] integerValue];
    //    NSLog(@"target Day:%d",day);
    
    NSDate *localeDate = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
    NSDate *curDate = [localeDate dateByAddingTimeInterval: interval];
    
    NSInteger curMonth = [[UIUtil getMonthFromDate:curDate] integerValue];
    //    NSLog(@"current Month:%d",curMonth);
    
    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
    //    NSLog(@"current Day:%d",curDay);
    
    NSInteger monthCha = curMonth - month;
    NSInteger dayCha = curDay - day;
    
    NSString *HMTime = [targetDate substringWithRange:NSMakeRange(12,5)];
    //当月
    if (monthCha == 0) {
        //当天
        if (dayCha == 0) {
            timeString = [NSMutableAttributedString attributeVenueStrWithText:@"今天\n" text2:HMTime color1:RGBCOLORWITH16COLOR(0x323232) color2:RGBCOLORWITH16COLOR(0x323232) font1:Font16 font2:Font14];
        }
        //昨天
        else if (dayCha == 1)
        {
            timeString = [NSMutableAttributedString attributeVenueStrWithText:@"昨天\n" text2:HMTime color1:RGBCOLORWITH16COLOR(0x323232) color2:RGBCOLORWITH16COLOR(0x323232) font1:Font16 font2:Font14];
        }
        //第三天至第七天之内（包含第七天）
        else if (dayCha > 1 && dayCha < 7)
        {
            timeString = [NSMutableAttributedString attributeVenueStrWithText:[NSString stringWithFormat:@"%@\n",[targetDate substringWithRange:NSMakeRange(8, 3)]] text2:[targetDate substringWithRange:NSMakeRange(5, 3)] color1:RGBCOLORWITH16COLOR(0x323232) color2:RGBCOLORWITH16COLOR(0x323232) font1:Font16 font2:Font14];

        }
        //大于七天
        else
        {
            timeString = [NSMutableAttributedString attributeVenueStrWithText:[NSString stringWithFormat:@"%@\n",[targetDate substringWithRange:NSMakeRange(8, 3)]] text2:[targetDate substringWithRange:NSMakeRange(5, 3)] color1:RGBCOLORWITH16COLOR(0x323232) color2:RGBCOLORWITH16COLOR(0x323232) font1:Font16 font2:Font14];
        }
    }
    //第二个月以上
    else
    {
        timeString = [NSMutableAttributedString attributeVenueStrWithText:[NSString stringWithFormat:@"%@\n",[targetDate substringWithRange:NSMakeRange(8, 3)]] text2:[targetDate substringWithRange:NSMakeRange(5, 3)] color1:RGBCOLORWITH16COLOR(0x323232) color2:RGBCOLORWITH16COLOR(0x323232) font1:Font18 font2:Font14];

    }
    return timeString;
}

+ (NSString *)timeForNewCommentListStyle:(NSDate *)theDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    formatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
    [formatter setDateFormat:@"MM月dd日 HH:mm"];
    NSString *targetDate = [formatter stringFromDate:theDate];
    
    return targetDate;
}

+ (NSString*)timeForParentChildRoomListStyle:(NSDate*) theDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *targetDate = [formatter stringFromDate:theDate];

    NSDateFormatter *f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d = [f dateFromString:targetDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSTimeInterval timeInterval=now-late;
    
    long temp = 0;
    NSString *result;
    if (timeInterval < 60) {
        result = [NSString stringWithFormat:@"刚刚"];
    }
    else if((temp = timeInterval/60) <60){
        result = [NSString stringWithFormat:@"%ld分钟前",temp];
    }
    
    else if((temp = temp/60) <24){
        result = [NSString stringWithFormat:@"%ld小时前",temp];
    }
    
    else if((temp = temp/24) <30){
        result = [NSString stringWithFormat:@"%ld天前",temp];
    }
    
    else if((temp = temp/30) <12){
        result = [NSString stringWithFormat:@"%ld月前",temp];
    }
    else{
        temp = temp/12;
        result = [NSString stringWithFormat:@"%ld年前",temp];
    }
    
    return  result;

//    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
//    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
//    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSString *targetDate = [formatter stringFromDate:theDate];
//    
//    NSDateFormatter *f = [[NSDateFormatter alloc] init];
//    [f setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
//    NSDate *d = [f dateFromString:targetDate];
//    [f release];
//    
//    NSTimeInterval late=[d timeIntervalSince1970]*1;
//    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
//    NSTimeInterval now=[dat timeIntervalSince1970]*1;
//    NSString*timeString=@"";
//    NSTimeInterval cha=now-late;
//
//    NSInteger day = [[targetDate substringWithRange:NSMakeRange(8, 2)] integerValue];
//    NSLog(@"target Day:%d",day);
//    
//    NSDate *localeDate = [NSDate date];
//    NSTimeZone *zone = [NSTimeZone systemTimeZone];
//    NSInteger interval = [zone secondsFromGMTForDate:localeDate];
//    NSDate *curDate = [localeDate dateByAddingTimeInterval: interval];
//    //NSLog(@"current Date:%@",curDate);
//    NSInteger curDay = [[UIUtil getDayFromDate:curDate] integerValue];
//    NSLog(@"current Day:%d",curDay);
//    
//    //时间在1小时之内
//    if(cha/3600<1) {
//        if (curDay-day == 1)
//        {
//            timeString = @"昨天";
//        }
//        else
//        {
//            if(cha/60<1) {
//                timeString = @"1";
//            }
//            else
//            {
//                timeString = [NSString stringWithFormat:@"%f", cha/60];
//                timeString = [timeString substringToIndex:timeString.length-7];
//            }
//            
//            timeString=[NSString stringWithFormat:@"%@分钟前", timeString];
//        }
//    }
//    //时间在1小时以上24小时以内
//    else if(cha/3600>1&&cha/86400<1) {
//        if (curDay-day == 1)
//        {
//            timeString = @"昨天";
//        }
//        else
//        {
//            timeString = [NSString stringWithFormat:@"%f", cha/3600];
//            timeString = [timeString substringToIndex:timeString.length-7];
//            timeString=[NSString stringWithFormat:@"%@小时前", timeString];
//        }
//    }
//    //时间在24小时以上5天以内
//    else if(cha/86400>1&&cha/(86400*5)<1)
//    {
//        if (curDay-day == 1)
//        {
//            timeString = @"昨天";
//        }
//        else
//        {
//            timeString=[NSString stringWithFormat:@"%d天前",curDay-day];
//        }
//    }
//    //时间大于5天
//    else
//    {
//        NSArray*array = [targetDate componentsSeparatedByString:@" "];
//        timeString = [array objectAtIndex:0];
//        timeString = [timeString substringWithRange:NSMakeRange(5, [timeString length]-5)];
//    }
//    
//    [formatter release];
//    return timeString;

}

+ (UIColor *)colorWithRGBHex:(UInt32)hex withAlpha:(float)alpha
{
	int r = (hex >> 16) & 0xFF;
	int g = (hex >> 8) & 0xFF;
	int b = (hex) & 0xFF;
    
	return [UIColor colorWithRed:r / 255.0f
						   green:g / 255.0f
							blue:b / 255.0f
						   alpha:alpha];
}

+ (UIColor *)colorWithHexString:(NSString *)stringToConvert withAlpha:(float)alpha
{
    NSString *hexString = [stringToConvert stringByReplacingOccurrencesOfString:@"#" withString:@""];
	NSScanner *scanner = [NSScanner scannerWithString:hexString];
	unsigned hexNum;
	if (![scanner scanHexInt:&hexNum]) return nil;
	return [self colorWithRGBHex:hexNum withAlpha:alpha];
}

+(UIImage *)setImageSize:(CGFloat)width imageName:(NSString *)imageName
{
	return [UIUtil setImageWidth:width height:width imageName:imageName];
}

+(UIImage *)setImageWidth:(CGFloat)width height:(CGFloat)height imageName:(NSString *)imageName
{
	//====================设置image的大小=========
	CGSize size = CGSizeMake(width, height);
	UIGraphicsBeginImageContext(size);
	UIImage *image = [UIImage imageNamed:imageName];
	[image drawInRect:CGRectMake(0,0, size.width, size.height)];
	image = UIGraphicsGetImageFromCurrentImageContext();
	UIGraphicsEndImageContext();
    return image;
	//===========================================
}

+ (UIImage *) captureView:(UIView *)theView
{
    UIGraphicsBeginImageContextWithOptions(theView.bounds.size, theView.opaque, 0.0);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
	
    UIImage * img = UIGraphicsGetImageFromCurrentImageContext();
	
    UIGraphicsEndImageContext();
	
    return img;
}

//+ (UIImage*)captureView:(UIView *)theView
//{
//	CGRect rect = theView.frame;
//	UIGraphicsBeginImageContext(rect.size);
//	CGContextRef context = UIGraphicsGetCurrentContext();
//	[theView.layer renderInContext:context];
//	UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
//	UIGraphicsEndImageContext();
//	return img;
//}

+ (void) hideHintMessageView:(id)arg {	
	UIView *view = (UIView*)arg;
	UIView *hintView = [view viewWithTag:kTagHintMessageView];
	if (hintView) {
		[hintView removeFromSuperview];
	}
}


+ (void) showHintMessage1:(NSString*) message withView:(UIView*) view{
	if (!view) {
		return;
	}
	UIView *hintView = [[UIView alloc] initWithFrame:view.bounds];
	hintView.tag = kTagHintMessageView;
	hintView.backgroundColor = [UIColor clearColor];
	hintView.alpha = 0;
	[view addSubview:hintView];
    //	UIImage *frameImage = [[UIImage imageNamed:@"alert_frameImg_light.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:0];
    //	UIImageView *bgView = [[UIImageView alloc] initWithImage:frameImage];
    //	bgView.frame = CGRectMake(hintView.bounds.origin.x + 18, hintView.bounds.size.height - 124, 293, 104);
    //	[hintView addSubview:bgView];
    //	[bgView release];
	
	CGFloat width = 220;
	CGFloat height = 50;
	CGFloat viewWidth = CGRectGetWidth(view.frame);
	CGFloat viewHeight = CGRectGetHeight(view.frame);
	CGFloat marginX = (viewWidth - width)/2;
	CGFloat marginY = (viewHeight - height)/2;
	UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(marginX, 20 , width, height)];
	bgView.backgroundColor = [UIColor groupTableViewBackgroundColor];
	bgView.layer.borderWidth = 2;
	bgView.layer.borderColor = [UIColor whiteColor].CGColor;
	bgView.layer.cornerRadius = 14;
	bgView.clipsToBounds = YES;
	[hintView addSubview:bgView];
	
	UIFont *font = [UIFont systemFontOfSize:14];
	CGSize boundingSize = CGSizeMake(width, CGFLOAT_MAX);
	CGSize requiredSize = [message sizeWithFont:font constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    
	marginY = (height - requiredSize.height)/2;
	marginX = (width - requiredSize.width)/2;
	UILabel	*hintLbl = [[UILabel alloc] initWithFrame:CGRectMake(marginX, marginY, requiredSize.width, requiredSize.height)];
	hintLbl.numberOfLines = (requiredSize.height)/[message sizeWithFont:font].height + 1;
	hintLbl.text = message;
	hintLbl.font = font;
	hintLbl.textAlignment = UITextAlignmentCenter;
	hintLbl.backgroundColor = [UIColor clearColor];
	hintLbl.lineBreakMode = UILineBreakModeWordWrap;
	hintLbl.textColor = [UIColor blackColor];
	
	[bgView addSubview:hintLbl];
    
	CATransform3D transform = CATransform3DMakeScale(0.001, 0.001, 1.0);
	bgView.layer.transform = transform;
	bgView.alpha = 0;
	transform = CATransform3DMakeScale(1.0, 1.0, 1.0);
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.3];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	bgView.layer.transform = transform;
	bgView.alpha = 1;
	hintView.alpha = 0.8;
	[UIView commitAnimations];
	[self performSelector:@selector(hideHintMessageView:) withObject:view afterDelay:2.0];
}


+ (void) showHintMessage:(NSString*) message withView:(UIView*) view{
	if (!view) {
		return;
	}
	UIView *hintView = [[UIView alloc] initWithFrame:view.bounds];	
	hintView.tag = kTagHintMessageView;
	hintView.backgroundColor = [UIColor clearColor];
	hintView.alpha = 0;
	[view addSubview:hintView];
    //	UIImage *frameImage = [[UIImage imageNamed:@"alert_frameImg_light.png"] stretchableImageWithLeftCapWidth:20 topCapHeight:0];
    //	UIImageView *bgView = [[UIImageView alloc] initWithImage:frameImage];
    //	bgView.frame = CGRectMake(hintView.bounds.origin.x + 18, hintView.bounds.size.height - 124, 293, 104);		
    //	[hintView addSubview:bgView];
    //	[bgView release];
	
	CGFloat width = 220;
	CGFloat height = 110;
	CGFloat viewWidth = CGRectGetWidth(view.frame);
	CGFloat viewHeight = CGRectGetHeight(view.frame);
	CGFloat marginX = (viewWidth - width)/2;
	CGFloat marginY = (viewHeight - height)/2;
	UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(marginX, marginY, width, height)];
	bgView.backgroundColor = [UIColor groupTableViewBackgroundColor];
	bgView.layer.borderWidth = 2;
	bgView.layer.borderColor = [UIColor whiteColor].CGColor;
	bgView.layer.cornerRadius = 14;
	bgView.clipsToBounds = YES;
	[hintView addSubview:bgView];
	
	UIFont *font = [UIFont systemFontOfSize:14];
	CGSize boundingSize = CGSizeMake(width, CGFLOAT_MAX);
	CGSize requiredSize = [message sizeWithFont:font constrainedToSize:boundingSize lineBreakMode:UILineBreakModeWordWrap];
    
	marginY = (height - requiredSize.height)/2;
	marginX = (width - requiredSize.width)/2;
	UILabel	*hintLbl = [[UILabel alloc] initWithFrame:CGRectMake(marginX, marginY, requiredSize.width, requiredSize.height)];
	hintLbl.numberOfLines = (requiredSize.height)/[message sizeWithFont:font].height + 1;
	hintLbl.text = message;
	hintLbl.font = font;
	hintLbl.textAlignment = UITextAlignmentCenter;
	hintLbl.backgroundColor = [UIColor clearColor];
	hintLbl.lineBreakMode = UILineBreakModeWordWrap;
	hintLbl.textColor = [UIColor blackColor];
	
	[bgView addSubview:hintLbl];
    
	CATransform3D transform = CATransform3DMakeScale(0.001, 0.001, 1.0);	
	bgView.layer.transform = transform;
	bgView.alpha = 0;
	transform = CATransform3DMakeScale(1.0, 1.0, 1.0);
	[UIView beginAnimations:nil context:nil];
	[UIView setAnimationDuration:0.3];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	bgView.layer.transform = transform;
	bgView.alpha = 1;
	hintView.alpha = 0.8;
	[UIView commitAnimations];
	[self performSelector:@selector(hideHintMessageView:) withObject:view afterDelay:2.0];
}

+ (NSDate*) dateFromFormat:(NSString*) timeString formate:(NSString*) formate {
	//static 
    NSDateFormatter *formatter = nil;
    if(formatter == nil)
    {
        formatter = [[NSDateFormatter alloc] init];
        [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
        [formatter setDateFormat:formate];
        NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
        [formatter setTimeZone:timeZone];
    }
	NSDate *date = [formatter dateFromString:timeString];
	return date;
}

+ (NSDate*) currentDate {
	time_t ct = time(NULL);
	struct tm *dt = localtime(&ct);
	int year = dt->tm_year + 1900;
	int month = dt->tm_mon + 1;
	int day = dt->tm_mday;
	int hour = dt->tm_hour;
	int minute = dt->tm_min;
	int second = dt->tm_sec;
	NSString *formate = @"yyyy-MM-dd HH:mm:ss";
	NSString *timeStr = [[NSString alloc] initWithFormat:@"%d-%d-%d %d:%d:%d", year, month, day, hour, minute, second];
	NSDate *date = [UIUtil dateFromFormat:timeStr formate:formate];
	return date;
}

//year, month, day
+ (NSString*) currentDateTimeYMDString {
	time_t ct = time(NULL);
	struct tm *dt = localtime(&ct);
	int year = dt->tm_year + 1900;
	int month = dt->tm_mon + 1;
	int day = dt->tm_mday;
	NSString *dateStr = [NSString stringWithFormat:@"%d年%d月%d日", year, month, day];
    
	return dateStr;
}

//year, month, day, weeks
+ (NSString*) currentDateTimeYMDWString {
	time_t ct = time(NULL);
	struct tm *dt = localtime(&ct);
	int wday = dt->tm_wday;
	NSString *dateStr = [UIUtil currentDateTimeYMDString];
	switch (wday) {
		case 1:	
			dateStr = [dateStr stringByAppendingString:@"星期一"];
			break;
		case 2:			
			dateStr = [dateStr stringByAppendingString:@"星期二"];
			break;
		case 3:			
			dateStr = [dateStr stringByAppendingString:@"星期三"];
			break;
		case 4:			
			dateStr = [dateStr stringByAppendingString:@"星期四"];
			break;
		case 5:			
			dateStr = [dateStr stringByAppendingString:@"星期五"];
			break;
		case 6:			
			dateStr = [dateStr stringByAppendingString:@"星期六"];
			break;
		case 7:			
			dateStr = [dateStr stringByAppendingString:@"星期日"];
			break;
		default:
			break;
	}
	return dateStr;
}

+ (NSString*) getYMDHMSDateString {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
	NSString *str = [formatter stringFromDate:date];
    return str;
}

+ (NSString*) getYMDHMSUTCDateString {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyy-MM-dd'T'hh:mm:ss'Z'"];
	NSString *str = [formatter stringFromDate:date];
    return str;
}

+ (NSString*) getCurrentTimeWithFormatYMDHMS {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyyMMddHHmmss"];
	NSString *str = [formatter stringFromDate:date];
    return str;
}

+ (NSString*) getYMDHMString {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"yyyy-MM-dd hh:mm"];
	NSString *str = [formatter stringFromDate:date];
    return str;
}

+ (NSString*) getHMString {
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:@"hh:mm"];
	NSString *str = [formatter stringFromDate:date];
    return str;
}

+ (NSString *) stringYMDFromMillisecond:(NSString *)millisecond{
	NSDate *date = [NSDate dateWithTimeIntervalSince1970:[millisecond intValue]];
	NSString *YMD = [self stringFromFomate:date formate:@"yyyy-MM-dd"];
	YMD = [self getYearMonthDayString:YMD];
	return YMD;
}

+ (NSString*) stringFromFomate:(NSDate*) date {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    //	[formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
	[formatter setDateFormat:@"yyyy-MM-dd hh:mm:ss"];
	NSString *str = [formatter stringFromDate:date];
	return str;
    
}

+ (NSString*) stringFromFomate:(NSDate*) date formate:(NSString*) formate {
	NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
	[formatter setDateFormat:formate];
	NSString *str = [formatter stringFromDate:date];
	return str;
}

+ (NSString*) currentDateTimeDetailString {
    time_t ct = time(NULL);
	struct tm *dt = localtime(&ct);
	int year = dt->tm_year + 1900;
	int month = dt->tm_mon + 1;
	int day = dt->tm_mday;
	int hour = dt->tm_hour;
	int minute = dt->tm_min;
	int second = dt->tm_sec;
    return [NSString stringWithFormat:@"%d-%02d-%02d %02d:%02d:%02d", year, month, day, hour, minute, second];
}

+ (NSString*) getHourFromDate:(NSDate*)date {
	NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
	unsigned flags = NSHourCalendarUnit;
	NSDateComponents *components = [calendar components:flags fromDate:date];
	NSString *hourStr = [NSString stringWithFormat:@"%ld", [components hour]];
	return hourStr;
}

+ (NSString*) getMinuteFromDate:(NSDate*)date {
	NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
	unsigned flags = NSMinuteCalendarUnit;
	NSDateComponents *components = [calendar components:flags fromDate:date];
	NSString *minuteStr = [NSString stringWithFormat:@"%ld", [components minute]];
	return minuteStr;
}

+ (NSString*) getDayFromDate:(NSDate*)date {
	NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
	unsigned flags = NSDayCalendarUnit;
	NSDateComponents *components = [calendar components:flags fromDate:date];
	NSString *dayStr = [NSString stringWithFormat:@"%ld", [components day]];
	return dayStr;
}

+ (NSString*) getMonthFromDate:(NSDate*)date {
	NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
	unsigned flags = NSMonthCalendarUnit;
	NSDateComponents *components = [calendar components:flags fromDate:date];
	NSString *monthStr = [NSString stringWithFormat:@"%ld", [components month]];
	return monthStr;
}

+ (NSString*) getYearFromDate:(NSDate*)date
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    [calendar setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
	unsigned flags = NSYearCalendarUnit;
	NSDateComponents *components = [calendar components:flags fromDate:date];
	NSString *yearStr = [NSString stringWithFormat:@"%ld", [components year]];
	return yearStr;
}

+ (NSString*) intervalStringBetweenCurrentDateWithDateString:(NSString*)dateString {
	NSString *intervalString;
	NSDate *date = [UIUtil dateFromFormat:dateString formate:@"yyyy-MM-dd HH:mm:ss"];	
	if ([UIUtil isCurrentDay:date]) {
        intervalString = [UIUtil stringFromFomate:date formate:@"HH:mm"];
        //		intervalString = [NSString stringWithFormat:@"%@:%@", [UIUtil getHourFromDate:date], [UIUtil getMinuteFromDate:date]];
	}
	else {
        //intervalString = [UIUtil stringFromFomate:date formate:@"MM-dd"]; //只显示月日	
        intervalString = [UIUtil stringFromFomate:date formate:@"yy-MM-dd"]; //只显示月日	
		//intervalString = [UIUtil stringFromFomate:date formate:@"yyyy-MM-dd HH:mm:ss"]; //显示时分
		//intervalString = [UIUtil stringFromFomate:date formate:@"MM-dd HH:mm"]; //显示时分 for bug 7245
        //		intervalString = [NSString stringWithFormat:@"%@-%@", [UIUtil getMonthFromDate:date], [UIUtil getDayFromDate:date]];		
	}
	return intervalString;
}

+ (CGSize) textSizeWithFont:(UIFont*) font width:(CGFloat) width height:(CGFloat)height text:(NSString *)text lineBreakMode:(NSLineBreakMode)breakMode
{
	CGSize boundingSize = CGSizeMake(width, height);
	CGSize requiredSize = [text sizeWithFont:font constrainedToSize:boundingSize lineBreakMode:breakMode];
	return requiredSize;
}

+ (NSString*) getYearMonthDayString:(NSString*)timeString {
	NSArray *ymds = [timeString componentsSeparatedByString:@"-"];
	NSString *ymdString = [NSString stringWithFormat:@"%@年%@月%@日", [ymds objectAtIndex:0], [ymds objectAtIndex:1], [[ymds objectAtIndex:2] substringToIndex:2]];
	return ymdString;
}

+ (void)setBGImageViewForView:(UIView *)view imageName:(NSString *)name{
	UIImageView *imageView = [[UIImageView alloc] initWithFrame:view.bounds];
	imageView.image = [UIImage imageNamed:name];
	[view addSubview:imageView];
}

+(void)alertToCustomMessage:(NSString*) msg
{
	
    
}


+ (void) showAlertMessage:(NSString*)title message:(NSString*)message {	
	if(!message) {
		UIAlertView *hintAlertView = [[UIAlertView alloc] initWithTitle:nil message:@"信息不能为空" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil];
		[hintAlertView show];
		return;
	}
    if(title == nil)
    {
        
    }
    
    
	UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
	[alertView show];
}

+ (void)addLineAtY:(CGFloat)y forView:(UIView *)view{
	UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10,y,300, 1)];
	lineView.backgroundColor = RGBCOLOR(0xC2,0xC2,0xC2);
	[view addSubview:lineView];
}

+ (NSString*) md5:(NSString *)str {
	const char *cStr = [str UTF8String];
	unsigned char result[CC_MD5_DIGEST_LENGTH];
	CC_MD5( cStr, strlen(cStr), result );
	return [[NSString  stringWithFormat:
             @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
             result[0], result[1], result[2], result[3], result[4],
             result[5], result[6], result[7],
             result[8], result[9], result[10], result[11], result[12],
             result[13], result[14], result[15]
             ] lowercaseString];
}

+ (BOOL) hasPrefix:(NSString *)str prefix:(NSString*)prefix {

    if(str.length < prefix.length)return NO;
	BOOL ret = NO;

    NSString* compare = [[str substringToIndex:prefix.length] lowercaseString];
    ret = [compare isEqualToString:[prefix lowercaseString]];
    
    return ret;
}

+ (BOOL) isHighResolutionDevice {
	float version = [[[UIDevice currentDevice] systemVersion] floatValue];
	if (version >= 4.0) { //iOS4
		UIScreen *mainScreen = [UIScreen mainScreen];
		if( mainScreen.scale>1 ){ //iPhone4
			//	[[NSUserDefaults standardUserDefaults] setBool:YES forKey:USERDEFAULT_SETTING_ISHDMODE];
		}
		return TRUE;
	}
	return FALSE;
}

+ (BOOL) isLandScape {
    UIDeviceOrientation o = [UIDevice currentDevice].orientation;
    return o == UIDeviceOrientationLandscapeLeft||o == UIDeviceOrientationLandscapeRight;
}

+ (BOOL) isCurrentDay:(NSDate*)date {
    BOOL result = TRUE;
    NSDate *currentDate = [NSDate date];
    NSCalendar *calendar = [NSCalendar currentCalendar];    
    
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    
    
    NSDateComponents *dateComps = [calendar components:unitFlags fromDate:currentDate];
    NSInteger year   = [dateComps year];
    NSInteger month  = [dateComps month];
    NSInteger day    = [dateComps day] - 1;
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    [comps setYear:year];
    [comps setMonth:month];
    [comps setDay:day];
    [comps setHour:24];
    [comps setMinute:0];
    [comps setSecond:0];    
    NSDate *zeroDate = [calendar dateFromComponents:comps];

    NSComparisonResult comparisonResult = [date compare:zeroDate];
   
    //date is eaylier than zerodate
    if (comparisonResult == NSOrderedAscending) {
        comparisonResult = [zeroDate compare:currentDate];        
        if (comparisonResult == NSOrderedAscending) {
            result = FALSE;
        }
    }
    return result;
}

+ (NSString*) getImageSize:(UIImage*) image {
    size_t width  = CGImageGetWidth(image.CGImage);
    size_t height = CGImageGetHeight(image.CGImage);
    size_t bitsPerPixel  =  CGImageGetBitsPerPixel(image.CGImage);
    CGFloat sizeOfKBytes = (width*height*bitsPerPixel)/(8*1024.0);
//    ITTDINFO(@"sizeOfKBytes%lf", sizeOfKBytes);
    return [NSString stringWithFormat:@"%.2lfKB", sizeOfKBytes];
}

+ (CGFloat) getImageSizeOfKB:(UIImage*) image {
    size_t width  = CGImageGetWidth(image.CGImage);
    size_t height = CGImageGetHeight(image.CGImage);
    size_t bitsPerPixel  =  CGImageGetBitsPerPixel(image.CGImage);
    CGFloat sizeOfKBytes = (width*height*bitsPerPixel)/(8*1024.0);
    return sizeOfKBytes;
}

// Return picture from contact
//+ (UIImage *) contactPicture:(ABRecordRef)person {
//    UIImage *headImage = nil;
//    // Check for contact picture
//    //    if (person != nil && ABPersonHasImageData(person)) {
//    //        CFDataRef dataRef = ABPersonCopyImageDataWithFormat(person, kABPersonImageFormatThumbnail);
//    //        if (dataRef) {
//    //            // iOS >= 4.1
//    //        }
//    //        else {
//    //            // iOS < 4.1
//    //            dataRef = ABPersonCopyImageData(person);
//    //        } 
//    //        if (dataRef) {
//    //            headImage = [UIImage imageWithData:(NSData *)dataRef];           
//    //            CFRelease(dataRef);
//    //        }
//    //    }
//    return headImage;
//}
//
//+ (ABRecordID) getMaxABRecordId {
//    ABRecordID recordId = -1;
//    ABRecordID currentRecordId;
//    ABAddressBookRef addressBook = ABAddressBookCreate();
//    CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople (addressBook);
//    for (id person in (NSArray *) allPeople) {   
//        currentRecordId = ABRecordGetRecordID(person);
//        if (currentRecordId > recordId) {
//            recordId = currentRecordId;
//        }
//    }
//    CFRelease(allPeople);
//    CFRelease(addressBook);
//    return recordId;
//}

+ (BOOL) isNetworkReachable {
    //check network connectivity
    BOOL result = TRUE;
    Reachability *hostReach = [Reachability reachabilityForInternetConnection];
    NetworkStatus connectionStatus = [hostReach currentReachabilityStatus];	
    if(connectionStatus == NotReachable){
        result = FALSE;
    }
    return result;
}

+ (void) showNetworkActivityIndicatorView:(UIView*) indicatorView show:(BOOL) show {
    [UIApplication sharedApplication].networkActivityIndicatorVisible = show;
	if (!indicatorView) {
		return;
	}
	UIView *contentView = (UIView*)[indicatorView viewWithTag:kTagIndicatorView];
	UIActivityIndicatorView *indicator = (UIActivityIndicatorView *)[indicatorView viewWithTag:kTagIndicator];
	if (!contentView) {
		contentView = [[UIView alloc] initWithFrame:[indicatorView bounds]];
		contentView.backgroundColor = RGBACOLORWithAlpha(100,100,100,0.7);
		contentView.tag = kTagIndicatorView;
        contentView.autoresizingMask = UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight;
		[indicatorView  addSubview:contentView];
		indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
		indicator.frame = CGRectMake((CGRectGetWidth(contentView.frame) - 30)/2, (CGRectGetHeight(contentView.frame) - 30)/2, 30, 30);
		indicator.tag = kTagIndicator;
        indicator.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin|UIViewAutoresizingFlexibleTopMargin|UIViewAutoresizingFlexibleBottomMargin;        
		[contentView addSubview:indicator];

	}
	if (show) {
		[contentView setHidden:NO];
		[indicator startAnimating];
		[indicatorView bringSubviewToFront:contentView];
	}
	else {
		[contentView setHidden:YES];
		[indicator stopAnimating];
		[indicatorView sendSubviewToBack:contentView];
	}
}

+ (NSString*)currentTime
{
	time_t ct = time(NULL);
	struct tm *dt = localtime(&ct);
	int year = dt->tm_year + 1900;
	int month = dt->tm_mon + 1;
	int day = dt->tm_mday;
	int hour = dt->tm_hour;
	int minute = dt->tm_min;
	//NSString *currTime = [[[NSString alloc] initWithFormat:@"%02d:%02d" , hour , minute] autorelease];
	NSString *currTime = [[NSString alloc] initWithFormat:@"%02d%02d" , hour , minute];
	return currTime;
}

+(NSString*)getValidEndTime:(NSString*)startTime EndTime:(NSString*)endTime
{
    if([startTime intValue] == [endTime intValue])//修改end
    {
        int iEndTime = [endTime intValue]+1;
        return [[NSString alloc]initWithFormat:@"%02d:00" , iEndTime];
    }
    return endTime;
}

+(NSString*)getValidStartTime:(NSString*)startTime EndTime:(NSString*)endTime
{
    if([startTime intValue] == [endTime intValue])//修改start
    {
        int iStartTime = [startTime intValue]-1;
        return [[NSString alloc]initWithFormat:@"%02d:00" , iStartTime];
    }
    return startTime;
}


+ (BOOL) currTimeInStartTime:(NSString*)startTime andEndTime:(NSString*)endTime
{
	NSArray *stimeArray = [startTime componentsSeparatedByString:@":"];
	NSArray *etimeArray = [endTime componentsSeparatedByString:@":"];
	NSString *hour = [stimeArray objectAtIndex:0];
	NSString *minute = [stimeArray objectAtIndex:1];
	NSString *sTime = [NSString stringWithFormat:@"%@%@", hour , minute];
    
	hour = [etimeArray objectAtIndex:0];
	minute = [etimeArray objectAtIndex:1];
	NSString *eTime = [NSString stringWithFormat:@"%@%@", hour , minute];
	
	NSInteger iStartTime = [sTime intValue];
	NSInteger iEndTime = [eTime intValue];	
	NSInteger iCurrTime = [[UIUtil currentTime] intValue];
    
	if(iStartTime < iEndTime)
	{
		if(iCurrTime >= iStartTime && iCurrTime <= iEndTime) //在静音范围内(在传入的时间段内)
		{
			return TRUE;
		}
		else
		{
			return FALSE;
		}
        
	}
	else if(iStartTime > iEndTime)
	{
		if((iCurrTime >= iStartTime && iCurrTime <= 2359) ||(iCurrTime >=0 && iCurrTime <= iEndTime) ) //在静音范围内(在传入的时间段内)
		{
			return TRUE;
		}
		return FALSE;
	}
	else if(iStartTime == iEndTime)
	{
		if(iCurrTime == iStartTime)
			return TRUE;
	}
	return FALSE;
}


+ (NSString*) ConvertFullFilePath:(NSString *)strBodyFile fileType:(NSInteger)type
{
    if(strBodyFile == NULL || [strBodyFile isEqualToString:@""])
        return (@"");
    NSRange range = [strBodyFile rangeOfString:@"/Documents/"];
    
    NSString *documentPath = [[NSString alloc] initWithFormat:@"%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    //NSString *homePath = NSHomeDirectory();
    NSString* strFullBodyPath = nil;
    if(range.location == NSNotFound)//新版，1.2版以上
    {
        //拼完整地址
        NSString *mailPath = NULL;
        if(type == TYPE_MAIL_DATA)
        {
            mailPath = [documentPath stringByAppendingPathComponent:@"MailData"];
        }            
        else
        {
            mailPath = [documentPath stringByAppendingPathComponent:@"AttachData"];
        }
        
        strFullBodyPath = [mailPath stringByAppendingPathComponent:strBodyFile];
        //strFullBodyPath = [documentPath stringByAppendingPathComponent:strBodyFile];
    }
    else
    {
        //替换app路径
        NSString *strBodyName = [strBodyFile substringFromIndex:range.location+range.length];
        NSString *mailPath = NULL;
        NSRange mailRange = [strBodyFile rangeOfString:@"MailData"];
        NSRange attachRange = [strBodyFile rangeOfString:@"AttachData"];
        
        mailPath = documentPath;
        if(type == TYPE_MAIL_DATA)
        {
            if(mailRange.location == NSNotFound)
                mailPath = [documentPath stringByAppendingPathComponent:@"MailData"];
        }
        else
        {
            if(attachRange.location == NSNotFound)
                mailPath = [documentPath stringByAppendingPathComponent:@"AttachData"];
        }
        
        //strFullBodyPath = [documentPath stringByAppendingPathComponent:strBodyName];
        strFullBodyPath = [mailPath stringByAppendingPathComponent:strBodyName];
        
    }
    return strFullBodyPath;
}

+ (NSString*) GetOldFullFilePath:(NSString *)strBodyFile
{
    if(strBodyFile == NULL || [strBodyFile isEqualToString:@""])
        return (@"");
    NSRange range = [strBodyFile rangeOfString:@"/Documents/"];
    
    NSString *documentPath = [[NSString alloc] initWithFormat:@"%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    NSString* strFullBodyPath = nil;
    if(range.location == NSNotFound)//新版，1.2版以上
    {
        //拼完整地址
        //        NSString *mailPath = NULL;
        //        if(type == TYPE_MAIL_DATA)
        //            mailPath = [documentPath stringByAppendingPathComponent:@"MailData"];
        //        else
        //            mailPath = [documentPath stringByAppendingPathComponent:@"AttachData"];
        //        strFullBodyPath = [mailPath stringByAppendingPathComponent:strBodyFile];
        strFullBodyPath = [documentPath stringByAppendingPathComponent:strBodyFile];
    }
    else
    {
        //替换app路径
        NSString *strBodyName = [strBodyFile substringFromIndex:range.location+range.length];
        //        NSString *mailPath = NULL;
        //        if(type == TYPE_MAIL_DATA)
        //            mailPath = [documentPath stringByAppendingPathComponent:@"MailData"];
        //        else
        //            mailPath = [documentPath stringByAppendingPathComponent:@"AttachData"];
        //        strFullBodyPath = [mailPath stringByAppendingPathComponent:strBodyName];
        strFullBodyPath = [documentPath stringByAppendingPathComponent:strBodyName];
    }
    return strFullBodyPath;
}


+ (NSString*) GetOnlyFileName:(NSString *)strBodyFile
{
    if(strBodyFile == NULL || [strBodyFile isEqualToString:@""])
        return (@"");
    NSRange range = [strBodyFile rangeOfString:@"/Documents/"];
    NSString* strFullBodyPath = nil;
    if(range.location == NSNotFound)//新版，1.2版以上
    {
        return strBodyFile;
    }
    else
    {
        //替换app路径
        NSString *strBodyName = [strBodyFile substringFromIndex:range.location+range.length];
        return strBodyName;
    }
    return strBodyFile;
}

+(BOOL) fileExistAtDocPath:(NSString*)fileName
{
    NSString *documentPath = [[NSString alloc] initWithFormat:@"%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    
    NSString* realPath = [documentPath stringByAppendingPathComponent:fileName];

    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL bExist = [fileManager fileExistsAtPath:realPath];
    return bExist;
}

+(NSString*) getDocumentPath
{
    NSString *documentPath = [[NSString alloc] initWithFormat:@"%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    return documentPath;
}

+(BOOL) moveCssFile:(NSInteger)csstype
{
    NSString *documentPath = [[NSString alloc] initWithFormat:@"%@", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0]];
    
    NSString* realPath = [documentPath stringByAppendingPathComponent:@"lt_ssr.css"];

    NSString* srcPathsmall =  [[NSBundle mainBundle]pathForResource:@"lt_ssr_small" ofType:@"css"];
    NSString* srcPathmiddle = [[NSBundle mainBundle]pathForResource:@"lt_ssr_middle" ofType:@"css"];
    NSString* srcPathlarge =  [[NSBundle mainBundle]pathForResource:@"lt_ssr_large" ofType:@"css"];
    
    NSString* srcPath = srcPathmiddle;
    switch(csstype)
    {
        case 0:
            srcPath = srcPathsmall;
            break;
        case 1:
            srcPath = srcPathmiddle;
            break;
        case 2:
            srcPath = srcPathlarge;
            break;
            
    }
    NSFileManager* fileManager = [NSFileManager defaultManager];
    BOOL bMoved = YES;
    //if (![fileManager fileExistsAtPath:realPath])
    //{
    
    NSError* error;
    
    BOOL bDelete = [fileManager removeItemAtPath:realPath error:&error];
    
    //if (![fileManager copyItemAtPath:srcPath toPath:realPath error:&error])
    bMoved = [fileManager copyItemAtPath:srcPath toPath:realPath error:&error];
    if (!bMoved)
    {
//        ITTDINFO(@"When copy css file: %@", [error localizedDescription]);
    }
    
    //}
    //    else {
    //        ITTDINFO(@"already exist!");
    //    }
    
//    ITTDINFO(@"css file at path:%@",realPath);
    return bMoved;
}


+(NSString*) MimeStringDateToStringDate:(NSString*) mimeDateStr
{
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
    
    //    NSString *dateStr = @"Fri, 25 Nov 2011 11:33:06 +0800";    
    [dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
    NSDate *date = [dateFormatter dateFromString:mimeDateStr];
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //用[NSDate date]可以获取系统当前时间
    NSString *convertDateStr = [dateFormatter stringFromDate:date];
    //输出格式为：2011-11-25 11:33:06
    //NSLog(@"%@",currentDateStr);

    return convertDateStr;
}

+(NSInteger) moveFileFrom:(NSString*)oldPath to:(NSString*)newPath
{
    const char *strFilePathOld = [oldPath UTF8String];
	const char *strFilePathNew = [newPath UTF8String];
    
    int ret = rename(strFilePathOld,strFilePathNew);
    return ret;
}

+(NSString*) filterDayString:(NSString*)dayStr
{
    NSRange range = [dayStr rangeOfString:@"天前"];
    
    if(range.location == NSNotFound)
        return dayStr;
    NSString *strDay = [dayStr substringToIndex:range.location];
    return strDay;
}

+(NSString*) AddDayString:(NSString*)dayStr
{
    NSRange range = [dayStr rangeOfString:@"天前"];
    
    if(range.location == NSNotFound)
    {
        NSString *strDay = [NSString stringWithFormat:@"%@%@" , dayStr , @"天前"];
        return strDay;
    }
    return dayStr;
}

+(NSInteger) getiOSSystemVersion
{
    float version = [[[UIDevice currentDevice] systemVersion] floatValue]; 
    if (version >= 4.0 && version < 5.0) 
    { 
        // iPhone 4.0 code here
        return IOS4;
    }
    else if(version >= 5.0 && version < 6.0)
    {
        return IOS5;
    }
    else if(version < 4.0)
    {
        return IOS3;
    }
    
    return (NSInteger)version;
}

+(NSInteger) getScreenWidth2
{
    UIDeviceOrientation orientation = [[UIDevice currentDevice] orientation];
    switch (orientation)
    {
        case UIDeviceOrientationLandscapeLeft:
        case UIDeviceOrientationLandscapeRight:
        {
            return HARDWARE_SCREEN_HEIGHT;
        }
            break;
        case UIDeviceOrientationPortrait:
        case UIDeviceOrientationPortraitUpsideDown:
        {
            return HARDWARE_SCREEN_WIDTH;
        }
            break;
        case UIDeviceOrientationFaceUp:
        case UIDeviceOrientationFaceDown:
        {
            UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
            switch(statusBarOrientation)
            {
                case UIInterfaceOrientationPortrait:
                case UIInterfaceOrientationPortraitUpsideDown:
                    return HARDWARE_SCREEN_WIDTH;
                case UIInterfaceOrientationLandscapeLeft:
                case UIInterfaceOrientationLandscapeRight:
                    return HARDWARE_SCREEN_HEIGHT;
            }
        }
            break;
        default:
            break;
    }
    return HARDWARE_SCREEN_WIDTH;
}


+(NSInteger) getScreenWidth
{
    UIInterfaceOrientation statusBarOrientation = [UIApplication sharedApplication].statusBarOrientation;
    switch(statusBarOrientation)
    {
        case UIInterfaceOrientationPortrait:
        case UIInterfaceOrientationPortraitUpsideDown:
            return HARDWARE_SCREEN_WIDTH;
        case UIInterfaceOrientationLandscapeLeft:
        case UIInterfaceOrientationLandscapeRight:
            return HARDWARE_SCREEN_HEIGHT;
    }
    return HARDWARE_SCREEN_WIDTH;
}    

+(NSString *)getTempPath:(NSString*)filename
{
    NSString *tempPath = NSTemporaryDirectory();
    return [tempPath stringByAppendingPathComponent:filename];
}


+(BOOL)isFileExist:(NSString *)filepath
{
    NSFileManager *filemanage = [NSFileManager defaultManager];
    return [filemanage fileExistsAtPath:filepath];
}

+(BOOL)copyFile:(NSString*)srcPath to:(NSString*)dstPath
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError* error;
    BOOL bCopied = [fileManager copyItemAtPath:srcPath toPath:dstPath error:&error];
    if (!bCopied)
    {
//        ITTDINFO(@"copyFile Error: %@", [error localizedDescription]);
    }
    return bCopied;
}

+(void) PostNotificationName:(NSString*)notificationName Object:(id)object Key:(id)key
{
    NSDictionary *userInfo = nil;
    if(object != nil)
        userInfo = [[NSDictionary alloc] initWithObjectsAndKeys:object, key, nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:userInfo];
}

// 功能： 获得文件的属性
// 参数： filePath：文件路径 ；
// 返回值： 文件属性字典
+(NSDictionary*)getFileAttributes:(NSString *)filePath
{
    // 获得文件管理句柄
    NSFileManager *manager = [NSFileManager defaultManager];
    // 获得文件属性字典
    NSError *err = nil;
    NSDictionary *attributes = [manager attributesOfItemAtPath:filePath error:&err];
    
    //        NSDictionary *filesystemattributes = [manager fileSystemAttributesAtPath:filePath];
    //        NSError *err = nil;
    //        NSDictionary *attributes = [manager fileAttributesAtPath:filePath traverseLink:NO];
    //        NSDictionary *filesystemattributesnew = [manager attributesOfFileSystemForPath:filePath error:&err];
    return attributes;
}

//功能：获得系统时间
//参数：无
//返回值：string类型时间
+(NSString *)getSystemTime:(NSDate*)date
{
    // 获取系统时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // 时间字符串
    //NSString *datestr = [dateFormatter stringFromDate:[NSDate date]];
    NSString *datestr = [dateFormatter stringFromDate:date];

    // 生成文件名
    NSString *string = [NSString stringWithFormat:@"%@",datestr];
    return string;
}
+(NSDate*)antiGetSystemTime:(NSString*)strDate
{
    // 获取系统时间
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
    [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    // 时间字符串
    //NSString *datestr = [dateFormatter stringFromDate:[NSDate date]];

    //[dateFormatter setLocale:[NSLocale systemLocale]];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

    NSDate* date = [dateFormatter dateFromString:strDate];

    // 生成文件名
    return date;
    
}


+(NSString*)getServerId:(NSString*)emailAddress
{
    NSRange domainRange = [emailAddress rangeOfString:@"@" options:NSBackwardsSearch];
    if(domainRange.location == NSNotFound)
    {
        return @"";
    }
    NSString *domainName = [emailAddress substringFromIndex:domainRange.location+1];
    NSRange dotRange = [domainName rangeOfString:@"." options:NSBackwardsSearch];
    NSString *serverId = [domainName substringToIndex:dotRange.location];
    return serverId;
}

+(NSString*)getDomain:(NSString*)emailAddress
{
    NSRange domainRange = [emailAddress rangeOfString:@"@" options:NSBackwardsSearch];
    if(domainRange.location == NSNotFound)
    {
        return @"";
    }
    NSString *domainName = [emailAddress substringFromIndex:domainRange.location];
    NSRange dotRange = [domainName rangeOfString:@"." options:NSBackwardsSearch];
    NSString *serverId = [domainName substringToIndex:dotRange.location];
    return serverId;
}

+(NSArray *)filterDomainAddress:(NSString *)domainString
{
    NSArray *emails = [domainString componentsSeparatedByString:@","];
    return emails;
}

+(NSString*)getDomainSuffix:(NSString*)emailAddress
{
    NSRange domainRange = [emailAddress rangeOfString:@"@" options:NSBackwardsSearch];
    if(domainRange.location == NSNotFound)
    {
        return @"";
    }
    NSString *domainSuffix = [emailAddress substringFromIndex:domainRange.location+1];
    return domainSuffix;
}


+(void)createAppPrivatePaths
{
    
}

+(void)addAlertViewTitle:(NSString*)title message:(NSString*)message delegate:(id)target cancelButtonTitle:(NSString*)cancelBtn otherBtnTitle:(NSString*)other
{
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:target cancelButtonTitle:cancelBtn otherButtonTitles:other, nil];
    [alert show];
}

+ (UIImage*)scaleFromImage:(UIImage*)image scaledToWidth:(CGFloat)newWidth
{
    CGSize imageSize = image.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    
    if (width<newWidth){
        return image;
    }
    
    CGFloat widthFactor = newWidth / width;
    
    CGFloat scaledWidth = newWidth;
    CGFloat scaledHeight = height * widthFactor;
    CGSize targetSize = CGSizeMake(scaledWidth,scaledHeight);
    
    UIGraphicsBeginImageContext(targetSize);
    [image drawInRect:CGRectMake(0,0,scaledWidth,scaledHeight)];
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

+(BOOL)isPlay
{
    int abc= [[UIUtil getHourFromDate:[NSDate date]] intValue];
    if (0<abc<14) {
        return YES;
    }
    return NO;
}

+(void)setMessageAlertFlag:(BOOL)flag
{
    [USER_DEFAULT setObject:[NSString stringWithFormat:@"%d",flag] forKey:@"MessageTips"];
}
+(void)setNotificationAlertFlag:(BOOL)flag
{
    [USER_DEFAULT setObject:[NSString stringWithFormat:@"%d",flag] forKey:@"NotificationSound"];
}
+(void)setVibrateAlertFlag:(BOOL)flag
{
    [USER_DEFAULT setObject:[NSString stringWithFormat:@"%d",flag] forKey:@"MessageAlert"];
}

+(BOOL)getMessageAlertFlag
{
    return [[USER_DEFAULT objectForKey:@"MessageTips"] boolValue];
}
+(BOOL)getNotificationAlertFlag
{
    return [[USER_DEFAULT objectForKey:@"NotificationSound"] boolValue];
}
+(BOOL)getVibrateAlertFlag
{
    return [[USER_DEFAULT objectForKey:@"MessageAlert"] boolValue];
}

+(void)setNoDisturbType:(uint)flag
{
    [USER_DEFAULT setValue:[NSString stringWithFormat:@"%d",flag] forKey:@"NO_DISTURB_TIME"];
}

+(NO_DISTURB_TIME)getNoDisturbType
{
    int no_disturb_time = [[USER_DEFAULT objectForKey:@"NO_DISTURB_TIME"] intValue];
    switch (no_disturb_time) {
        case 0:
            return ALL_DAY;
            break;
        case 1:
            return ONLY_NIGHT;
            break;
        case 2:
            return CLOSE_ALL_TIME;
            break;
        default:
            return CLOSE_ALL_TIME;
            break;
    }
}

+(void)playSystemAlert
{
    
    // Register the sound completion callback.
    AudioServicesAddSystemSoundCompletion(kSystemSoundID_Vibrate,
                                          NULL, // uses the main run loop
                                          NULL, // uses kCFRunLoopDefaultMode
                                          IMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
                                          NULL // for user data, but we don't need to do that in this case, so we just pass NULL
                                          );
    
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    
}


+(SystemSoundID)playSystemSoundForMessage
{
    // 要播放的音频文件地址
    NSURL *bundlePath = [[NSBundle mainBundle] URLForResource:@"eFeng" withExtension:@"bundle"];
    if (!bundlePath) {
        return 0;
    }
    NSURL *audioPath = [[NSBundle bundleWithURL:bundlePath] URLForResource:@"in" withExtension:@"caf"];
    // 创建系统声音，同时返回一个ID，若直接播放会造成静音状态下也能播放声音
    SystemSoundID soundID;
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(audioPath), &soundID);
    // Register the sound completion callback.
    AudioServicesAddSystemSoundCompletion(soundID,
                                          NULL, // uses the main run loop
                                          NULL, // uses kCFRunLoopDefaultMode
                                          IMSystemSoundFinishedPlayingCallback, // the name of our custom callback function
                                          NULL // for user data, but we don't need to do that in this case, so we just pass NULL
                                          );
    
    AudioServicesPlaySystemSound(soundID);
    
    return soundID;

}
+(void)playSystemSoundForNotification
{
    //自定义消息提示音
    SystemSoundID sourceID ;
//    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"11" ofType:@"wav"];
    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"三全音" ofType:@"wav"];
//    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"message_voice" ofType:@"wav"];
//    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"3751" ofType:@"mp3"];
//    NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"可疑声音" ofType:@"mp3"];
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundFile], &sourceID);
    AudioServicesPlaySystemSound(sourceID);
    
    //系统提示音
//    AudioServicesPlaySystemSound(1000);
//    AudioServicesPlaySystemSound(1003);
//    AudioServicesPlaySystemSound(1006);
//    AudioServicesPlaySystemSound(1007);
//    AudioServicesPlaySystemSound(1008);
//    AudioServicesPlaySystemSound(1009);
//    AudioServicesPlaySystemSound(1010);
//    AudioServicesPlaySystemSound(1013);
//    AudioServicesPlaySystemSound(1014);
//    AudioServicesPlaySystemSound(1015);
//    AudioServicesPlaySystemSound(1321);

}

//发送声音  按下声音
+(void)playSoundForVoiceAnXia:(AudioServicesSystemSoundCompletionProc)proc{
    if ([UIUtil getNotificationAlertFlag]) {
        //自定义消息提示音
        SystemSoundID sourceID ;
        NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"anxia" ofType:@"wav"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundFile], &sourceID);
       // AudioServicesPlaySystemSound(sourceID);
        AudioServicesAddSystemSoundCompletion(sourceID, NULL,NULL, proc,NULL);
       // [NSThread sleepForTimeInterval:.5f];

    }
}

+(void)playSoundForVoiceAnXia{
    if ([UIUtil getNotificationAlertFlag]) {
        //自定义消息提示音
        SystemSoundID sourceID ;
        NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"anxia" ofType:@"wav"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundFile], &sourceID);
         AudioServicesPlaySystemSound(sourceID);
        
    }
}

//发送声音 松开声音
+(void)playSoundForVoiceSongKai{
    if ([UIUtil getNotificationAlertFlag]) {
        //自定义消息提示音
        SystemSoundID sourceID ;
        NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"songkai" ofType:@"wav"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundFile], &sourceID);
        AudioServicesPlaySystemSound(sourceID);

    }
    
}
//发送声音  声音发送成功
+(void)playSoundForVoiceSuccess{
    if ([UIUtil getNotificationAlertFlag]) {
        SystemSoundID sourceID ;
        NSString *soundFile = [[NSBundle mainBundle] pathForResource:@"yifasong" ofType:@"wav"];
        AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:soundFile], &sourceID);
        AudioServicesPlaySystemSound(sourceID);
    }
    
}


+(void)playSound
{
    //在判断免打扰时间段，
        //提醒，判断是否开启相应功能
        //不提醒返回空
    switch ([UIUtil getNoDisturbType]) {
        case ALL_DAY:
            break;
        case ONLY_NIGHT:
            //仅夜间关闭
            //添加时间控制
            if ([self isPlay]) {
                if ([UIUtil getNotificationAlertFlag]) {
                    [UIUtil playSystemSoundForNotification];
                }
                if ([UIUtil getVibrateAlertFlag]) {
                    [UIUtil playSystemAlert];
                }
            }
            break;
        case CLOSE_ALL_TIME:
            //关闭免打扰
            if ([UIUtil getNotificationAlertFlag]) {
                [UIUtil playSystemSoundForNotification];
            }
            if ([UIUtil getVibrateAlertFlag]) {
                [UIUtil playSystemAlert];
            }
            break;
        default:
            break;
    }
}


+(void)playWave
{
    //在判断免打扰时间段，
    //提醒，判断是否开启相应功能
    //不提醒返回空
    switch ([UIUtil getNoDisturbType]) {
        case ALL_DAY:
            break;
        case ONLY_NIGHT:
            //仅夜间关闭
            //添加时间控制
            if ([self isPlay]) {
                if ([UIUtil getVibrateAlertFlag]) {
                    [UIUtil playSystemAlert];
                }
            }
            break;
        case CLOSE_ALL_TIME:
            //关闭免打扰
            if ([UIUtil getVibrateAlertFlag]) {
                [UIUtil playSystemAlert];
            }
            break;
        default:
            break;
    }
}

+(void)createFilePath:(NSString *)filePath
{
    if(filePath == nil)
    {
        return;
    }
    if(![filePath hasSuffix:@"/"])
    {
        NSRange range = [filePath rangeOfString:@"/" options:NSBackwardsSearch];
        if(range.location != NSNotFound)
        {
            filePath = [filePath substringToIndex:range.location];
        }
        
    }
    
    
    NSFileManager* defaultManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    BOOL existed = [defaultManager fileExistsAtPath: filePath isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) )
    {
        [defaultManager createDirectoryAtPath: filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }

}

+(void)LogToFile:(NSString *)content
{
    NSString *fileName = [NSString stringWithFormat:@"%@_log.log", [UIUtil getStrByDate:0]];
    //    NSString *sZipPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/t21刘元涛20150315.zip"];
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/log/%@", fileName]];
    NSString *filePath1 = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/log"]];
//    [content writeToFile:sZipPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
//    BOOL isExit = [NLCommonUtil isExitOfFile:@"nonotextiphone"];
//    NSString *filePath = [self FilePathInDocumentByFileName:@"nonotextiphone"];
    BOOL isExit = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!isExit) {
        if(![[NSFileManager defaultManager] fileExistsAtPath:filePath1])
        {
            [[NSFileManager defaultManager] createDirectoryAtPath:filePath1 withIntermediateDirectories:YES attributes:nil error:nil];
        }
        
//        NSLog(@"%@",@"文件不存在");
        NSString *s = [NSString stringWithFormat:@"开始了:\r\n"];
        [s writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    }
    
    NSFileHandle  *outFile;
    NSData *buffer;
    
    outFile = [NSFileHandle fileHandleForWritingAtPath:filePath];
    
    if(outFile == nil)
    {
        NSLog(@"Open of file for writing failed");
    }
    
    //找到并定位到outFile的末尾位置(在此后追加文件)
    [outFile seekToEndOfFile];
//    NSString* file = [[NSString alloc] initWithFormat:@"%s", __FILE__];
    //读取inFile并且将其内容写到outFile中
    NSString *bs = [NSString stringWithFormat:@"%@ %@ ", [UIUtil stringFromFomate:[NSDate date]],content];
    buffer = [bs dataUsingEncoding:NSUTF8StringEncoding];
    
    [outFile writeData:buffer];  
    
    //关闭读写文件  
    [outFile closeFile];
}


+(NSString *)getStrByDate:(NSInteger)index
{
    NSTimeInterval  oneDay = 24*60*60*1;  //1天的长度
    NSDate *date = [NSDate date];
    NSDate *newDate = [date initWithTimeIntervalSinceNow:oneDay*index ];
    //实例化一个NSDateFormatter对象
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //设定时间格式,这里可以设置成自己需要的格式
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    //用[NSDate date]可以获取系统当前时间
    NSString *currentDateStr = [dateFormatter stringFromDate:newDate];
    //输出格式为：2010-10-27 10:22:13
//    NSLog(@"%@",currentDateStr);
    //alloc后对不使用的对象别忘了release
    //    [dateFormatter release];
    return currentDateStr;
}

+(void)delOldLog
{
    
    NSString *filePath1 = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/log"]];
    if(![[NSFileManager defaultManager] fileExistsAtPath:filePath1])
    {
        return;
    }

    NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:5];
    for(int i = 0; i > -5; i--)
    {
        NSString *fileName = [NSString stringWithFormat:@"%@_log.log", [UIUtil getStrByDate:i]];
        [array addObject:fileName];
    }
    NSArray *files = [[NSFileManager defaultManager] subpathsAtPath: filePath1 ];
    for(NSString *file in files)
    {
        if(file == nil || [file length] == 0)
        {
            continue;
        }
        if([array indexOfObject:file ] == NSNotFound)
        {
            [[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@/%@", filePath1, file] error:nil];
        }
    }
}
+ (NSArray *)handleFilePathWithPath:(NSString *)path isGroup:(BOOL)isGroup
{
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSString *subPath in array) {
        NSString *filePath = [path stringByAppendingPathComponent:subPath];
        BOOL isdir = NO;
        [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isdir];
        if (isdir){
            
        } else {
            
            NSDictionary* properties = [[NSFileManager defaultManager]
                                        attributesOfItemAtPath:filePath
                                        error:nil];
        
            int64_t fileSize = [properties fileSize];
            
            int64_t realSize = [[CXmppRequestMgr shareInstance].downMgr loadFileWihtServerFileName:filePath.lastPathComponent].FileSize;
            if (realSize > 0 && realSize == fileSize) {
                
                NSString *timeStr = [NSString stringWithFormat:@"%f",[[properties objectForKey:NSFileModificationDate] timeIntervalSince1970] * 1000];
                NSRange range = [timeStr rangeOfString:@"."];
                NSString* modDate = [timeStr substringToIndex:range.location];
                
                CFileModel *fileModel = [[CFileModel alloc] init];
                fileModel.CreateDate = modDate;
                fileModel.serverFileName = filePath.lastPathComponent;
                fileModel.FileSize = fileSize;
                if (isGroup) {
                    fileModel.FileName = [self getGroupFileNameWithServerFileName:fileModel.serverFileName];
                } else {
                    fileModel.FileName = [self getFileNameWithServerFileName:fileModel.serverFileName];
                }
                fileModel.LocalFilePath = filePath;
                fileModel.isDir = NO;
                [arrayM addObject:fileModel];

            } else {
            
            }

        }
    }
    return arrayM;
}



+ (NSArray *)handleDirPathWithPath:(NSString *)path
{
    NSArray *array = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:nil];
    NSMutableArray *arrayM = [NSMutableArray array];
    for (NSString *subPath in array) {
        NSString *filePath = [path stringByAppendingPathComponent:subPath];
        BOOL isdir = NO;
        [[NSFileManager defaultManager] fileExistsAtPath:filePath isDirectory:&isdir];
        if (isdir){
            [self handleDirPathWithPath:filePath];
        } else {
            NSLog(@"%@",filePath);
        }
    }
    return arrayM;
}

+ (NSString *)getChatFileIconByName:(NSString *)fileName
{
    if(M_ISSTRNULL(fileName))
    {
        return nil;
    }
    NSString *fileIcon = @"icon-what";
    
    if([fileName hasSuffix:@".xls"] || [fileName hasSuffix:@".xlsx"])
    {
        fileIcon = @"icon-excel";
    }
    else if([fileName hasSuffix:@".doc"] || [fileName hasSuffix:@".docx"])
    {
        fileIcon = @"icon-word";
    }
    else if([fileName hasSuffix:@".txt"] )
    {
        fileIcon = @"icon-txt";
    }
    else if([fileName hasSuffix:@".jpg"] || [fileName hasSuffix:@".png"]|| [fileName hasSuffix:@".bmp"] || [fileName hasSuffix:@".jpeg"])
    {
        fileIcon = @"icon-image";
    }
    else if([fileName hasSuffix:@".mp4"] )
    {
        fileIcon = @"icon-movie";
    }
    else if([fileName hasSuffix:@".pdf"])
    {
        fileIcon = @"icon-pdf";
    }
    else if([fileName hasSuffix:@".ppt"] || [fileName hasSuffix:@".pptx"])
    {
        fileIcon = @"icon-ppt";
    }
    else if([fileName hasSuffix:@".rar"] || [fileName hasSuffix:@".zip"])
    {
        fileIcon = @"icon-zip";
    } else if ([fileName hasSuffix:@".wav"] || [fileName hasSuffix:@".amr"] || [fileName hasSuffix:@".mp3"]) {
        fileIcon = @"icon-mp3";
    }
    
    
    return fileIcon;

}

+(NSString *)getFileIconByName:(NSString *)fileName
{
    
    if(M_ISSTRNULL(fileName))
    {
        return nil;
    }
    
    fileName = [fileName lowercaseString];
    NSString *fileIcon = @"othersIcon";
    if([fileName hasSuffix:@".xls"] || [fileName hasSuffix:@".xlsx"])
    {
        fileIcon = @"execlIcon";
    }
    else if([fileName hasSuffix:@".doc"] || [fileName hasSuffix:@".docx"])
    {
        fileIcon = @"wordIcon";
    }
    else if([fileName hasSuffix:@".txt"] )
    {
        fileIcon = @"txtIcon";
    }
    else if([fileName hasSuffix:@".jpg"] || [fileName hasSuffix:@".png"]|| [fileName hasSuffix:@".bmp"] || [fileName hasSuffix:@".jpeg"])
    {
        fileIcon = @"imageIcon";
    }
    else if([fileName hasSuffix:@".mp4"] )
    {
        fileIcon = @"mp4Icon";
    }
    else if([fileName hasSuffix:@".pdf"])
    {
        fileIcon = @"pdfIcon";
    }
    else if([fileName hasSuffix:@".ppt"] || [fileName hasSuffix:@".pptx"])
    {
        fileIcon = @"pptIcon";
    }
    else if([fileName hasSuffix:@".rar"] || [fileName hasSuffix:@".zip"])
    {
        fileIcon = @"rarIcon";
    } else if ([fileName hasSuffix:@".wav"] || [fileName hasSuffix:@".amr"] || [fileName hasSuffix:@".mp3"]) {
        fileIcon = @"file_wav";
    }


    return fileIcon;
}


+ (NSString *)getGroupFileNameWithServerFileName:(NSString *)serverFileName
{
    NSRange strRange = NSMakeRange(0, 0);
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"___" options:NSRegularExpressionCaseInsensitive error:nil];
      NSArray *results = [regex matchesInString:serverFileName options:NSMatchingReportCompletion range:NSMakeRange(0, serverFileName.length)];
    if (results.count == 0) {
    } else { // 匹配成功
        int i = 0;
        for (NSTextCheckingResult *result in results) {
//            NSString *range = NSStringFromRange(result.range);
            if (i == 1) {
                strRange = result.range;
                break;
            }
            i++;
//            NSLog(@"%@ %@", range, [serverFileName substringWithRange:result.range]);
        }
    }
    return M_STOREVALUE([serverFileName substringFromIndex:(strRange.location + strRange.length)]);
}

+ (NSString *)getFileNameWithServerFileName:(NSString *)serverFileName
{
//    NSArray *array = [serverFileName componentsSeparatedByString:@"___"];
//    if (array.count > 0) {
//        return array.lastObject;
//    } else {
//        return serverFileName;
//    }
        NSRange strRange = NSMakeRange(0, 0);
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"___" options:NSRegularExpressionCaseInsensitive error:nil];
    NSArray *results = [regex matchesInString:serverFileName options:NSMatchingReportCompletion range:NSMakeRange(0, serverFileName.length)];
    if (results.count == 0) {
        
    } else { // 匹配成功
        int i = 0;
        for (NSTextCheckingResult *result in results) {
//            NSString *range = NSStringFromRange(result.range);
            if (i == 0) {
                strRange = result.range;
                break;
            }
            i ++;
//            NSLog(@"%@ %@", range, [serverFileName substringWithRange:result.range]);
        }
    }
    return M_STOREVALUE([serverFileName substringFromIndex:(strRange.location + strRange.length)]);
}


+ (NSString *)getOverdueYMDHMSDateStringWithTimeStamp:(NSDate *)date
{

    NSDateFormatter *fom = [[NSDateFormatter alloc] init];
    fom.locale = [NSLocale currentLocale];
    fom.dateFormat = @"yyyy-MM-dd";
    return [fom stringFromDate:date];
}

+ (NSString *)getCurrentTimeStamp
{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] *1000 + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    NSString *timeStr = [NSString stringWithFormat:@"%f",time];
    NSRange range = [timeStr rangeOfString:@"."];
    
    return [timeStr substringToIndex:range.location];
}


+ (NSDateComponents *)getCurdateComponents
{
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970] * 1000 + [[USER_DEFAULT stringForKey:SERVER_TIME_SYS] doubleValue];
    NSDate *curDate = [NSDate dateWithTimeIntervalSince1970:time / 1000.0];
    NSCalendar *canlendar = [NSCalendar currentCalendar];
    canlendar.locale = [NSLocale currentLocale];
    canlendar.timeZone = [NSTimeZone systemTimeZone];
    NSDateComponents *cmp = [canlendar components:NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute fromDate:curDate];
    return cmp;
}

@end
